package yueyong.salarymanagement.module.business.salary.controller;

import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import yueyong.salarymanagement.common.anno.NoValidPrivilege;
import yueyong.salarymanagement.common.constant.ResponseCodeConst;
import yueyong.salarymanagement.common.domain.ResponseDTO;
import yueyong.salarymanagement.constant.SwaggerTagConst;
import yueyong.salarymanagement.module.business.salary.domain.dto.EmployeeAndSalarySendDTO;
import yueyong.salarymanagement.module.business.salary.domain.entity.EmployeeSalaryEntity;
import yueyong.salarymanagement.module.business.salary.domain.vo.EmployeeAndSalaryVO;
import yueyong.salarymanagement.module.business.salary.domain.vo.MessageSendResultVO;
import yueyong.salarymanagement.module.business.salary.service.EmployeeSalaryService;
import yueyong.salarymanagement.module.system.login.domain.RequestTokenBO;
import yueyong.salarymanagement.util.SmartRequestTokenUtil;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * Copyright: yueyong (c) 2022
 *
 * @author he.shaorong
 * @version 1.0
 * @date 2022/2/6
 */
@RestController
@Api(tags = {SwaggerTagConst.Admin.BUSINESS})
public class SalaryHomePageController {

    @Autowired
    private EmployeeSalaryService employeeSalaryService;


    @GetMapping("/user/getMessageSendResult")
    @ApiOperation(value = "首页 查询首页信息", notes = "查询最近一条salaryId微信，短信，邮件发送情况")
    @NoValidPrivilege
    public ResponseDTO<MessageSendResultVO> getMessageSendResult() {
        MessageSendResultVO resultVO = new MessageSendResultVO();

        RequestTokenBO requestToken = SmartRequestTokenUtil.getRequestUser();
        Long uid = requestToken.getRequestUserId();

        List<EmployeeSalaryEntity> latestEmployeeSalaryEntityList = employeeSalaryService.getLatestEmployeeSalaryEntity(uid);
        //没有数据返回0
        if (latestEmployeeSalaryEntityList == null || latestEmployeeSalaryEntityList.size() == 0) {
            return ResponseDTO.succData(resultVO);
        }
        long salaryId = latestEmployeeSalaryEntityList.get(0).getSalaryId();

        List<EmployeeSalaryEntity> salaryEntityList = employeeSalaryService.getEmployeeSalaryEntityBySalaryId(uid, salaryId);
        if (salaryEntityList == null || salaryEntityList.size() == 0) {
            return ResponseDTO.wrap(ResponseCodeConst.NOT_EXISTS);
        }

        resultVO.setSalarySlipId(salaryId);
        resultVO.setEdmTotalCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 2).count());
        resultVO.setEdmSuccessCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 2 && item.getState() == 0).count());
        resultVO.setEdmErrorCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 2 && item.getState() == 1).count());
        resultVO.setShortMessageTotalCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 4).count());
        resultVO.setShortMessageSuccessCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 4 && item.getState() == 0).count());
        resultVO.setShortMessageErrorCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 4 && item.getState() == 1).count());
        resultVO.setWeChatTotalCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 1).count());
        resultVO.setWeChatSuccessCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 1 && item.getState() == 0).count());
        resultVO.setWeChatErrorCount((int) salaryEntityList.stream().filter(item -> item.getSendType() == 1 && item.getState() == 1).count());

        return ResponseDTO.succData(resultVO);
    }

    @ApiOperation(value = "首页 获取员工，薪资发放情况", notes = "人员变动，累计发放薪资情况")
    @PostMapping("/user/queryEmployeeAndSalaryInfo")
    @NoValidPrivilege
    public ResponseDTO<List<EmployeeAndSalaryVO>> queryEmployeeAndSalaryInfo(@Valid @RequestBody EmployeeAndSalarySendDTO employeeAndSalarySendDTO) {
        List<EmployeeAndSalaryVO> list = Lists.newArrayList();
        for (int i = 0; i < 12; i++) {
            LocalDateTime dateStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN)
                    .plusMonths(1).minusMonths(12 - i).minusDays(1);
            LocalDateTime dateEnd = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN)
                    .plusMonths(1).minusMonths(11 - i).minusDays(1);
            EmployeeAndSalaryVO result = getSpecifyDateStatic(dateStart, dateEnd, employeeAndSalarySendDTO.getSendType());
            list.add(result);
        }
        return ResponseDTO.succData(list);
    }

    private EmployeeAndSalaryVO getSpecifyDateStatic(LocalDateTime dateStart, LocalDateTime dateEnd, int sendType) {

        EmployeeAndSalaryVO employeeAndSalaryVO = new EmployeeAndSalaryVO();

        Timestamp startTime = Timestamp.valueOf(dateStart);
        Timestamp endTime = Timestamp.valueOf(dateEnd);

        RequestTokenBO requestToken = SmartRequestTokenUtil.getRequestUser();
        Long uid = requestToken.getRequestUserId();
        employeeAndSalaryVO.setCountDate(startTime.getTime());


        List<EmployeeSalaryEntity> salaryEntityList = employeeSalaryService.getSpecifyDateEmployeeSalaryEntity(startTime, endTime, uid, sendType);
        if (salaryEntityList == null || salaryEntityList.size() == 0) {
            return employeeAndSalaryVO;
        }
        employeeAndSalaryVO.setSendEmployeeCount(salaryEntityList.size());
        employeeAndSalaryVO.setPayAmountCount(salaryEntityList.stream()
                .map(EmployeeSalaryEntity::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        return employeeAndSalaryVO;
    }
}
